//
//  JKFileExplorerViewController.m
//  TestCocoaHTTPserver
//
//  Created by albert on 2018/11/8.
//  Copyright © 2018 albert. All rights reserved.
//

#import "JKFileExplorerViewController.h"
#import "JKFileExploreCollectionViewCell.h"
#import "JKExplorerReusableView.h"
#import "JKFileManager.h"
#import "JKFileExplorerEngine.h"
#import "JKFileExplorerWebViewController.h"
#import "JKFileExplorerItem.h"
#import "NSBundle+JKFileExplorer.h"
#import "JKFileExplorerPreviewController.h"
#import "JKFileExploreCollectionView.h"

#import "JKWebServerManager.h"
#import "SSZipArchive.h"

#import "JKCircularProgressView.h"

#import "JKFileExplorerManager.h"
#import "JKFileExplorerDownloadTaskViewController.h"
#import "JKFileExplorerTextEditViewController.h"
#import "JKFileExplorerAirDropShareManager.h"

//#import "JKWebServerViewController.h"

@interface JKFileExplorerViewController () <
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UISearchBarDelegate,
UIDocumentInteractionControllerDelegate,
UIDocumentPickerDelegate,
JKWebServerManagerDelegate>
{
    CGSize RowSize;
    CGSize SquareSize;
}

/** fileNewItems */
@property (nonatomic, strong) NSMutableArray *fileNewItems;

/** filePathItemDict */
@property (nonatomic, strong) NSMutableDictionary *filePathItemDict;

/** collectionView */
@property (nonatomic, weak) JKFileExploreCollectionView *collectionView;

/** footerHeight */
@property (nonatomic, assign) CGFloat footerHeight;

/** fileItemArr */
@property (nonatomic, strong) NSMutableArray *fileItemArr;

/** indicatorView */
@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;

/** selectButton */
@property (nonatomic, weak) UIButton *selectButton;

/** addButton */
@property (nonatomic, weak) UIButton *addButton;

/** 选中的文件 */
@property (nonatomic, copy) NSString *selectedFilePath;

/** docVc */
@property (nonatomic, strong) UIDocumentInteractionController *docVc;

/** searchText */
@property (nonatomic, copy) NSString *searchText;

/** searchFileItemArr */
@property (nonatomic, strong) NSMutableArray *searchFileItemArr;

/** 是否展示搜索结果 */
@property (nonatomic, assign) BOOL showSearchResult;

/** currentMoreAtionFileItem */
@property (nonatomic, strong) JKFileExplorerItem *currentMoreAtionFileItem;

/** 显示Wifi传输信息的按钮 */
@property (nonatomic, weak) UIButton *wifiTransferButton;

/** Wifi传输的地址 */
@property (nonatomic, copy) NSString *wifiTransferAddress;

/** 粘贴按钮 */
@property (nonatomic, weak) UIButton *pasteButton;

/** 取消操作文件按钮 */
@property (nonatomic, weak) UIButton *cancelOperateFileButton;

/** selectedFileItems */
@property (nonatomic, strong) NSMutableArray *selectedFileItems;

/** fileNameTextField */
@property (nonatomic, weak) UITextField *fileNameTextField;

/** diskSizeInfoLabel */
@property (nonatomic, weak) UILabel *diskSizeInfoLabel;

/** filePreviewItemArr */
@property (nonatomic, strong) NSMutableArray *filePreviewItemArr;

/** searchFilePreviewItemArr */
@property (nonatomic, strong) NSMutableArray *searchFilePreviewItemArr;
@end

@implementation JKFileExplorerViewController

+ (void)showWithViewController:(UIViewController *)viewController{
    
    JKFileExplorerViewController *vc = [[JKFileExplorerViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
    if (viewController && [viewController isKindOfClass:[UIViewController class]]) {
        
        [viewController presentViewController:nav animated:YES completion:nil];
        
        return;
    }
    
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 生命周期

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self stopWifiTransfer];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}

- (void)dealloc{
    
    [self stopWifiTransfer];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSString *)currentDirectory{
    
    return self.fileItem.filePath;
}

#pragma mark
#pragma mark - 初始化

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addOperateFileNotifications];
    
    [self addOutsideOperateFileNotifications];
    
    NSString *navTitle = nil;
    
    if (self.navTitle) {
        
        navTitle = self.navTitle;
        
    } else {
        
        navTitle = self.fileItem.fileName;
        
        if (self.isRootViewController) {
            
            navTitle = [_directoryPath isEqualToString:NSHomeDirectory()] ? @"Home" : [_directoryPath lastPathComponent];
        }
    }
    
    self.navigationItem.title = navTitle;
    
    RowSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 60);
    CGFloat squareItemWH = ([UIScreen mainScreen].bounds.size.width - 0.5) / 3;
    SquareSize = CGSizeMake(squareItemWH, squareItemWH);
    
    [self adjustFooterHeight];
    
    [self buildUI];
    
    [self layoutUI];
    
    [self loadData];
}

- (void)layoutUI{
    /*
     self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
     
     NSLayoutConstraint *collectionViewLeft = [NSLayoutConstraint constraintWithItem:self.collectionView attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1 constant:0];
     [self.view addConstraint:collectionViewLeft];
     
     NSLayoutConstraint *collectionViewRight = [NSLayoutConstraint constraintWithItem:self.collectionView attribute:(NSLayoutAttributeRight) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeRight) multiplier:1 constant:0];
     [self.view addConstraint:collectionViewRight];
     
     NSLayoutConstraint *collectionViewTop = [NSLayoutConstraint constraintWithItem:self.collectionView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeTop) multiplier:1 constant:0];
     [self.view addConstraint:collectionViewTop];
     
     NSLayoutConstraint *collectionViewBottom = [NSLayoutConstraint constraintWithItem:self.collectionView attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeBottom) multiplier:1 constant:0];
     [self.view addConstraint:collectionViewBottom]; //*/
    
    self.collectionView.frame = [UIScreen mainScreen].bounds;
    
    self.tipLabel.frame = CGRectMake(15, (self.view.frame.size.height - 60) * 0.5 - self.collectionView.contentInset.top + 106, (self.view.frame.size.width - 30), 60);
    self.indicatorView.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5 - self.collectionView.contentInset.top + 106);
    
    self.tabBar.frame = CGRectMake(0, self.view.frame.size.height - (self.isIphoneX ? 83 : 49), self.view.frame.size.width, (self.isIphoneX ? 83 : 49));
    
    self.selectButton.frame = CGRectMake(0, 0, 49, 49);
    
    self.addButton.frame = CGRectMake(self.tabBar.frame.size.width - 49, 0, 49, 49);
    
    self.pasteButton.frame = self.selectButton.frame;
    self.cancelOperateFileButton.frame = self.addButton.frame;
    
    self.diskSizeInfoLabel.frame = CGRectMake(15, JKIsIphoneX ? 98 : 74, CGRectGetWidth(self.collectionView.frame) - 30, 300);
}

- (void)buildUI{
    
    UIImage *letItemImage = _isRootViewController ? [NSBundle jk_imageWithName:@"nav_close@3x" type:@"png"] : [NSBundle jk_imageWithName:@"nav_back@3x" type:@"png"];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:letItemImage style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemClick)];
    
    UIImage *rightItemImage = _arrangeType == JKFileExplorerArrangeTypeSquare ? [NSBundle jk_imageWithName:@"nav_list@3x" type:@"png"] : [NSBundle jk_imageWithName:@"nav_square@3x" type:@"png"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightItemImage style:(UIBarButtonItemStylePlain) target:self action:@selector(rightItemClick)];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    JKFileExploreCollectionView *collectionView = [[JKFileExploreCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.backgroundColor = nil;
    [self.view addSubview:collectionView];
    _collectionView = collectionView;
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.alwaysBounceVertical = YES;
    
    [collectionView registerClass:[JKFileExploreCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([JKFileExploreCollectionViewCell class])];
    [collectionView registerClass:[JKExplorerReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JKExplorerReusableView class])];
    [collectionView registerClass:[JKExplorerReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    
    collectionView.contentInset = self.isIphoneX ? UIEdgeInsetsMake(88, 0, 83, 0) : UIEdgeInsetsMake(64, 0, 49, 0);
    collectionView.scrollIndicatorInsets = collectionView.contentInset;
    
    SEL selector = NSSelectorFromString(@"setContentInsetAdjustmentBehavior:");
    
    if ([collectionView respondsToSelector:selector]) {
        
        IMP imp = [collectionView methodForSelector:selector];
        void (*func)(id, SEL, NSInteger) = (void *)imp;
        func(collectionView, selector, 2);
        
        // [tbView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2)];
    }
    
    [self.collectionView insertSubview:self.tipLabel atIndex:0];
    
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    [self.collectionView insertSubview:indicatorView aboveSubview:self.tipLabel];
    _indicatorView = indicatorView;
    
    [self tabBar];
    
    UIButton *selectButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [selectButton setTitle:@"选择" forState:(UIControlStateNormal)];
    [self.tabBar addSubview:selectButton];
    _selectButton = selectButton;
    
    [selectButton addTarget:self action:@selector(selectButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UIButton *addButton = [UIButton buttonWithType:(UIButtonTypeContactAdd)];
    [self.tabBar addSubview:addButton];
    _addButton = addButton;
    
    [addButton addTarget:self action:@selector(addButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UIButton *pasteButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    
    [pasteButton setTitle:@"粘贴" forState:(UIControlStateNormal)];
    pasteButton.hidden = YES;
    [self.tabBar addSubview:pasteButton];
    _pasteButton = pasteButton;
    
    [pasteButton addTarget:self action:@selector(pasteButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    UIButton *cancelOperateFileButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [cancelOperateFileButton setTitle:@"取消" forState:(UIControlStateNormal)];
    cancelOperateFileButton.hidden = YES;
    [self.tabBar addSubview:cancelOperateFileButton];
    _cancelOperateFileButton = cancelOperateFileButton;
    
    [cancelOperateFileButton addTarget:self action:@selector(cancelOperateFileButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UILabel *diskSizeInfoLabel = [[UILabel alloc] init];
    diskSizeInfoLabel.font = [UIFont systemFontOfSize:12];
    diskSizeInfoLabel.textColor = [UIColor lightGrayColor];
    diskSizeInfoLabel.numberOfLines = 0;
    diskSizeInfoLabel.textAlignment = NSTextAlignmentCenter;
    [self.view insertSubview:diskSizeInfoLabel atIndex:0];
    _diskSizeInfoLabel = diskSizeInfoLabel;
}

#pragma mark
#pragma mark - 加载数据

- (BOOL)isAllBlankString:(NSString *)string{
    
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    
    NSString *trimedString = [string stringByTrimmingCharactersInSet:set];
    
    return trimedString.length == 0;
}

- (BOOL)isValidDirectory{
    
    if (!_directoryPath ||
        [_directoryPath isEqualToString:@""] ||
        [self isAllBlankString:_directoryPath]) {
        
        return NO;
    }
    
    return YES;
}

- (void)loadData{
    
    /*
     if (![self isValidDirectory]) {
     
     NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"无效路径"}];
     
     self.navigationItem.title = @"无效路径";
     
     [self handleCreateFileItemError];
     
     [self handleError:error];
     
     return;
     } //*/
    
    [self.indicatorView startAnimating];
    
    if (self.isRootViewController) {
        
        // 获取home路径的item
        [JKFileExplorerEngine fetchFileItemWithDirectoryPath:self.directoryPath finish:^(NSString *directoryPath, JKFileExplorerItem *fileItem) {
            
            self.fileItem = fileItem;
            
            //            if (self.fileItem.createItemError) {
            //
            //                [self handleCreateFileItemError];
            //
            //                [self handleError:self.fileItem.createItemError];
            //
            //                return;
            //            }
            
            [self preloadFileItemList];
        }];
        
    } else {
        
        [self preloadFileItemList];
    }
}

- (void)preloadFileItemList{
    
    if (self.fileItem.fetchSubFileNameListError) { // 已经有错误信息
        
        [self handleError:self.fileItem.fetchSubFileNameListError];
        
    } else { // 无错误信息
        
        if (self.fileItem.subFileNameList) { // 有字文件名列表
            
            [self loadFileItemList];
            
        } else { // 无字文件名列表
            
            [JKFileExplorerEngine fetchFileNameListWithFileItem:self.fileItem success:^(JKFileExplorerItem *fileItem, NSArray<NSString *> *fileNameList) {
                
                [self loadFileItemList];
                
            } failure:^(NSError *error) {
                
                [self handleError:error];
            }];
        }
    }
}

- (void)loadFileItemList{
    
    [JKFileExplorerEngine fetchFileItemListWithDirectoryPath:self.fileItem.filePath fileNameList:self.fileItem.subFileNameList sortConfig:self.sortConfig success:^(NSString *directoryPath, NSArray<JKFileExplorerItem *> *fileItemList, NSArray<JKFileExplorerItem *> *folderList, NSArray<JKFileExplorerItem *> *fileList, NSMutableDictionary *filePathItemDict) {
        
        [self.indicatorView stopAnimating];
        
        [self solveDataWithDirectoryPath:directoryPath fileItemList:fileItemList folderList:folderList fileList:fileList filePathItemDict:filePathItemDict];
        
        [self checkDiskSize];
    }];
}

#pragma mark
#pragma mark - 处理数据

- (void)solveDataWithDirectoryPath:(NSString *)directoryPath
                      fileItemList:(NSArray<JKFileExplorerItem *> *)fileItemList
                        folderList:(NSArray<JKFileExplorerItem *> *)folderList
                          fileList:(NSArray<JKFileExplorerItem *> *)fileList
                  filePathItemDict:(NSMutableDictionary *)filePathItemDict{
    
    self.fileItem.subTotalCount  = fileItemList.count;
    self.fileItem.subFolderCount = folderList.count;
    self.fileItem.subFileCount   = fileList.count;
    
    self.filePathItemDict = filePathItemDict;
    
    !self.fileItem.fileInfoDidChange ? : self.fileItem.fileInfoDidChange(self.fileItem);
    
    [self adjustFooterHeight];
    
    [self.fileItemArr removeAllObjects];
    [self.fileItemArr addObjectsFromArray:fileItemList];
    
    [self.filePreviewItemArr removeAllObjects];
    [self.filePreviewItemArr addObjectsFromArray:fileList];
    
    NSIndexPath *fileNewItemIndexPath = nil;
    
    if (self.fileNewItemPath) {
        
        JKFileExplorerItem *fileNewItem = [self.filePathItemDict objectForKey:self.fileNewItemPath];
        self.fileNewItemPath = nil;
        
        if (fileNewItem) {
            
            [self.fileNewItems addObject:fileNewItem];
            
            fileNewItem.isNew = YES;
            
            if ([self.fileItemArr containsObject:fileNewItem]) {
                
                NSInteger index = [self.fileItemArr indexOfObject:fileNewItem];
                
                fileNewItemIndexPath = [NSIndexPath indexPathForItem:index inSection:0];
            }
        }
    }
    
    [self.collectionView reloadData];
    
    [self adjustCollectionContentOffset];
    
    self.tipLabel.text = @"empty";
    self.tipLabel.hidden = (self.fileItemArr.count > 0);
    
    if (self.operatingFileItems) {
        
        [self setOperatingFileItems:self.operatingFileItems];
    }
    
    if (fileNewItemIndexPath) {
        
        [self.collectionView scrollToItemAtIndexPath:fileNewItemIndexPath atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
    }
}

- (void)handleCreateFileItemError{
    
    self.tabBar.userInteractionEnabled = NO;
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)handleError:(NSError *)error{
    
    [self.indicatorView stopAnimating];
    
    self.tipLabel.text = error.localizedDescription;
    self.tipLabel.hidden = NO;
    
    [self.collectionView reloadData];
    
    if (self.operatingFileItems) {
        
        [self setOperatingFileItems:self.operatingFileItems];
    }
    
    [self performSelector:@selector(adjustCollectionContentOffset) withObject:nil afterDelay:0.1];
}

#pragma mark
#pragma mark - 处理footer及contentOffset

- (void)adjustFooterHeight{
    
    if (self.arrangeType == JKFileExplorerArrangeTypeSquare) {
        
        self.footerHeight = [UIScreen mainScreen].bounds.size.height - ((self.isIphoneX ? (88 + 83) : (64 + 49)) + 50);
        
        NSInteger itemCount = (self.showSearchResult ? self.searchFileItemArr.count : self.fileItem.subTotalCount);
        
        CGFloat totalRowHeight = itemCount == 0 ? 0 : (((itemCount - 1) / 3 + 1) * SquareSize.height);
        
        self.footerHeight -= totalRowHeight;
        
    } else {
        
        self.footerHeight = [UIScreen mainScreen].bounds.size.height - ((self.isIphoneX ? (88 + 83) : (64 + 49)) + 50);
        
        self.footerHeight -= (self.showSearchResult ? self.searchFileItemArr.count : self.fileItem.subTotalCount) * self->RowSize.height;
    }
}

- (void)adjustCollectionContentOffset{
    
    [self.collectionView setContentOffset:CGPointMake(0, -self.collectionView.contentInset.top + 106) animated:NO];
}

#pragma mark
#pragma mark - 磁盘使用情况

- (void)checkDiskSize{
    
    [JKFileExplorerEngine checkDiskSizeComplete:^(NSString *totalSize, NSString *usedSize, NSString *freeSize) {
        
        long long bgmSize = 0;
        
        int fileCount = 0;
        
        for (JKFileExplorerItem *md in self.fileItemArr) {
            
            if (md.isFolder) { continue; }
            
            bgmSize += [md.fileSize longLongValue];
            
            fileCount++;
        }
        
        NSString *bgmSizeStr = [NSByteCountFormatter stringFromByteCount:bgmSize countStyle:(NSByteCountFormatterCountStyleFile)];
        
        NSString *desStr = [NSString stringWithFormat:@"当前目录共%d个文件，占用空间%@\n磁盘总空间: %@\n已使用空间: %@\n剩余空间: %@", fileCount, bgmSizeStr, totalSize, usedSize, freeSize];
        
        NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
        para.lineSpacing = 8;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSAttributedString *attr = [[NSAttributedString alloc] initWithString:desStr attributes:@{NSForegroundColorAttributeName : self.diskSizeInfoLabel.textColor, NSFontAttributeName : self.diskSizeInfoLabel.font, NSParagraphStyleAttributeName : para}];
            
            self.diskSizeInfoLabel.attributedText = attr;
            
            CGRect rect = self.diskSizeInfoLabel.frame;
            
            CGSize size = [self.diskSizeInfoLabel sizeThatFits:CGSizeMake(CGRectGetWidth(rect), INFINITY)];
            
            rect.size.height = size.height;
            
            self.diskSizeInfoLabel.frame = rect;
        });
    }];
}

#pragma mark
#pragma mark - 重新排序

- (void)resort{
    
    [JKFileExplorerEngine sortFileItemList:self.fileItemArr sortConfig:self.sortConfig finish:^(NSArray<JKFileExplorerItem *> *fileItemList, NSArray<JKFileExplorerItem *> *folderList, NSArray<JKFileExplorerItem *> *fileList) {
        
        [self.indicatorView stopAnimating];
        
        self.fileItem.subTotalCount  = fileItemList.count;
        self.fileItem.subFolderCount = folderList.count;
        self.fileItem.subFileCount   = fileList.count;
        
        [self adjustFooterHeight];
        
        [self.fileItemArr removeAllObjects];
        [self.fileItemArr addObjectsFromArray:fileItemList];
        
        [self.filePreviewItemArr removeAllObjects];
        [self.filePreviewItemArr addObjectsFromArray:fileList];
        
        self.tipLabel.text = self.fileItem.fetchSubFileNameListError ? self.fileItem.subTotalCountString : (self.showSearchResult ? @"no result" : @"empty");
        self.tipLabel.hidden = self.showSearchResult ? (self.searchFileItemArr.count > 0) : (self.fileItemArr.count > 0);
        
        if (self.showSearchResult) { // 显示搜索结果
            
            [self startSearchWithText:self.searchText];
            
        } else {
            
            [self.collectionView reloadData];
            
            if (self.fileNewItems.count > 0) {
                
                NSIndexPath *indexPathNew = nil;
                
                if ([self.fileItemArr containsObject:self.fileNewItems.firstObject]) {
                    
                    NSInteger index = [self.fileItemArr indexOfObject:self.fileNewItems.firstObject];
                    
                    indexPathNew = [NSIndexPath indexPathForItem:index inSection:0];
                }
                
                if (indexPathNew) {
                    
                    [self.collectionView scrollToItemAtIndexPath:indexPathNew atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
                }
            }
        }
        
        [self checkDiskSize];
    }];
}

#pragma mark
#pragma mark - 点击事件

- (void)leftItemClick{
    
    if (self.isRootViewController) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightItemClick{
    
    _arrangeType = (_arrangeType == JKFileExplorerArrangeTypeRow) ? JKFileExplorerArrangeTypeSquare : JKFileExplorerArrangeTypeRow;
    
    switch (_arrangeType) {
        case JKFileExplorerArrangeTypeSquare:
        {
            self.navigationItem.rightBarButtonItem.image = [NSBundle jk_imageWithName:@"nav_list@3x" type:@"png"];
        }
            break;
            
        default:
        {
            self.navigationItem.rightBarButtonItem.image = [NSBundle jk_imageWithName:@"nav_square@3x" type:@"png"];
        }
            break;
    }
    
    [self adjustFooterHeight];
    
    [self.collectionView reloadData];
}

- (void)segmentClick:(UISegmentedControl *)segment{
    
    JKFileExplorerSortConfig config = self.sortConfig;
    
    switch (segment.selectedSegmentIndex) {
        case 0:
        {
            config.sortIdentifier = JKFileExplorerSortIdentifierFileName;
        }
            break;
        case 1:
        {
            config.sortIdentifier = JKFileExplorerSortIdentifierFileSize;
        }
            break;
        case 2:
        {
            config.sortIdentifier = JKFileExplorerSortIdentifierCreateDate;
        }
            break;
        case 3:
        {
            config.sortIdentifier = JKFileExplorerSortIdentifierModificationDate;
        }
            break;
            
        default:
            break;
    }
    
    self.sortConfig = config;
    
    [self resort];
}

- (void)sortFoderButtonClick:(UIButton *)button{
    
    JKFileExplorerSortConfig sortConfig = self.sortConfig;
    
    switch (self.sortConfig.folderLocation) {
        case JKFileExplorerSortFolderLocationTop:
        {
            sortConfig.folderLocation = JKFileExplorerSortFolderLocationMix;
            
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_mix"] forState:(UIControlStateNormal)];
        }
            break;
        case JKFileExplorerSortFolderLocationMix:
        {
            sortConfig.folderLocation = JKFileExplorerSortFolderLocationBottom;
            
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_bottom"] forState:(UIControlStateNormal)];
        }
            break;
        case JKFileExplorerSortFolderLocationBottom:
        {
            sortConfig.folderLocation = JKFileExplorerSortFolderLocationTop;
            
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_top"] forState:(UIControlStateNormal)];
        }
            break;
            
        default:
            break;
    }
    
    self.sortConfig = sortConfig;
    
    [self updateFolderLocationIconWithButton:button];
    
    [self resort];
}

/** 更新文件位置按钮的图标 */
- (void)updateFolderLocationIconWithButton:(UIButton *)button{
    
    switch (self.sortConfig.folderLocation) {
        case JKFileExplorerSortFolderLocationTop:
        {
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_top"] forState:(UIControlStateNormal)];
        }
            break;
        case JKFileExplorerSortFolderLocationMix:
        {
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_mix"] forState:(UIControlStateNormal)];
        }
            break;
        case JKFileExplorerSortFolderLocationBottom:
        {
            [button setImage:[NSBundle jk_imageWithName:@"folder_location_bottom"] forState:(UIControlStateNormal)];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark
#pragma mark - 切换正/倒序

- (void)descAscButtonClick:(UIButton *)button{
    button.selected = !button.selected;
    
    JKFileExplorerSortConfig sortConfig = self.sortConfig;
    
    sortConfig.sortType = (button.selected ? JKFileExplorerSortTypeDesc : JKFileExplorerSortTypeAsc);
    
    self.sortConfig = sortConfig;
    
    [self resort];
}

#pragma mark
#pragma mark - 选择

- (void)selectButtonClick:(UIButton *)button{
    
    if ([button.currentTitle isEqualToString:@"选择"]) {
        
        [button setTitle:@"完成" forState:(UIControlStateNormal)];
        
        [self enterEditingMode];
        
    } else {
        
        [button setTitle:@"选择" forState:(UIControlStateNormal)];
        
        [self exitEditingMode];
    }
}

- (void)selectAllItemClick:(UIBarButtonItem *)item{
    
    if ([item.title isEqualToString:@"全选"]) {
        
        item.title = @"取消全选";
        
        [self executeSelectAll];
        
    } else {
        
        item.title = @"全选";
        
        [self executeCancelSelectAll];
    }
}

- (void)executeSelectAll{
    
    [self.selectedFileItems removeAllObjects];
    
    if (self.showSearchResult) {
        
        [self.searchFileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.selected = YES;
            
            [self.selectedFileItems addObject:obj];
        }];
        
    } else {
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.selected = YES;
            
            [self.selectedFileItems addObject:obj];
        }];
    }
    
    [self.collectionView reloadData];
}

- (void)executeCancelSelectAll{
    
    if (self.showSearchResult) {
        
        [self.searchFileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.selected = NO;
        }];
        
    } else {
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.selected = NO;
        }];
    }
    
    [self.selectedFileItems removeAllObjects];
    
    [self.collectionView reloadData];
}

#pragma mark
#pragma mark - 进入/退出编辑模式

- (void)enterEditingMode{
    
    [self stopWifiTransfer];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:(UIBarButtonItemStylePlain) target:self action:@selector(selectAllItemClick:)];
    
    self.isEditing = YES;
    
    [self.selectedFileItems removeAllObjects];
    
    self.currentMoreAtionFileItem = nil;
    
    // 当前显示的cell做动画
    for (JKFileExploreCollectionViewCell *cell in self.collectionView.visibleCells) {
        
        [cell enterEditingModeAnimated:YES];
    }
    
    if (self.showSearchResult) {
        
        [self.searchFileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.isEditing = YES;
        }];
        
    } else {
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.isEditing = YES;
        }];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionView reloadData];
    });
}

- (void)exitEditingMode{
    
    [self.selectButton setTitle:@"选择" forState:(UIControlStateNormal)];
    
    UIImage *letItemImage = _isRootViewController ? [NSBundle jk_imageWithName:@"nav_close@3x" type:@"png"] : [NSBundle jk_imageWithName:@"nav_back@3x" type:@"png"];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:letItemImage style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemClick)];
    
    [self.selectedFileItems removeAllObjects];
    
    self.isEditing = NO;
    
    // 当前显示的cell做动画
    for (JKFileExploreCollectionViewCell *cell in self.collectionView.visibleCells) {
        
        [cell exitEditingModeAnimated:YES];
    }
    
    if (self.showSearchResult) {
        
        [self.searchFileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.isEditing = NO;
            obj.selected = NO;
        }];
        
    } else {
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            obj.isEditing = NO;
            obj.selected = NO;
        }];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.collectionView reloadData];
    });
}

#pragma mark
#pragma mark - <UICollectionViewDataSource, UICollectionViewDelegate>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.showSearchResult ? self.searchFileItemArr.count : self.fileItemArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    JKFileExploreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([JKFileExploreCollectionViewCell class]) forIndexPath:indexPath];
    
    cell.arrangeType = self.arrangeType;
    
    if (indexPath.item < (self.showSearchResult ? self.searchFileItemArr.count : self.fileItemArr.count)) {
        
        JKFileExplorerItem *fileItem = [(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) objectAtIndex:indexPath.item];
        
        cell.fileItem = fileItem;
        
    } else {
        
        NSLog(@"cellForItemAtIndexPath数组越界了! count-->%ld, indexPath.item-->%ld", (self.showSearchResult ? self.searchFileItemArr.count : self.fileItemArr.count), indexPath.item);
        
        NSLog(@"数组越界navigationController-->%@", self.navigationController);
    }
    
    [self solveCellClick:cell];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (_arrangeType) {
        case JKFileExplorerArrangeTypeSquare:
        {
            return SquareSize;
        }
            break;
            
        default:
        {
            return RowSize;
        }
            break;
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        
        footer.backgroundColor = self.view.backgroundColor;
        
        return footer;
    }
    
    JKExplorerReusableView *sectionHeader = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JKExplorerReusableView class]) forIndexPath:indexPath];
    
    sectionHeader.backgroundColor = self.view.backgroundColor;
    
    UILabel *catalogueLabel = [sectionHeader viewWithTag:102];
    
    if (!catalogueLabel) {
        
        catalogueLabel = [self buildSectionHeader:sectionHeader];
    }
    
    UISearchBar *searchBar = [sectionHeader viewWithTag:101];
    
    if (self.showSearchResult) {
        
        searchBar.text = self.searchText;
    }
    
    UISegmentedControl *segment = [sectionHeader viewWithTag:103];
    segment.selectedSegmentIndex = self.sortConfig.sortIdentifier;
    
    UIButton *sortFoderButton = [sectionHeader viewWithTag:104];
    [self updateFolderLocationIconWithButton:sortFoderButton];
    
    UIButton *descButton = [sectionHeader viewWithTag:105];
    descButton.selected = self.sortConfig.sortType == JKFileExplorerSortTypeDesc;
    
    NSString *currentFilePathInfo = [NSString stringWithFormat:@"%@\n共%lu项，%lu文件夹，%lu文件", self.fileItem.relativePath, (unsigned long)self.fileItem.subTotalCount, (unsigned long)self.fileItem.subFolderCount, (unsigned long)self.fileItem.subFileCount];
    
    catalogueLabel.text = currentFilePathInfo;
    
    return sectionHeader;
}

- (UILabel *)buildSectionHeader:(JKExplorerReusableView *)sectionHeader{
    
    UIView *searchContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 46)];
    [sectionHeader insertSubview:searchContainerView atIndex:0];
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:searchContainerView.bounds];
    searchBar.tag = 101;
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    [searchContainerView addSubview:searchBar];
    
    UILabel *catalogueLabel = [[UILabel alloc] init];
    catalogueLabel.frame = CGRectMake(15, CGRectGetMaxY(searchContainerView.frame), [UIScreen mainScreen].bounds.size.width - 30, 60);
    catalogueLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
    catalogueLabel.font = [UIFont systemFontOfSize:11];
    catalogueLabel.numberOfLines = 0;
    catalogueLabel.tag = 102;
    [sectionHeader addSubview:catalogueLabel];
    
    UIView *sortWayContainerView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(catalogueLabel.frame), [UIScreen mainScreen].bounds.size.width, 50)];
    [sectionHeader addSubview:sortWayContainerView];
    
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"名称", @"大小", @"创建日期", @"修改日期"]];
    segment.tag = 103;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat itemWidth = screenWidth > 375 ? 70 : (screenWidth > 320 ? 65 : 60);
    segment.frame = CGRectMake((screenWidth - itemWidth * 4) * 0.5, 10, itemWidth * 4, 30);
    [sortWayContainerView addSubview:segment];
    
    [segment addTarget:self action:@selector(segmentClick:) forControlEvents:(UIControlEventValueChanged)];
    
    UIButton *sortFoderButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    sortFoderButton.tag = 104;
    sortFoderButton.frame = CGRectMake(segment.frame.origin.x - 24 - (itemWidth > 60 ? 13 : 8), 13, 24, 24);
    [sortWayContainerView addSubview:sortFoderButton];
    
    [sortFoderButton addTarget:self action:@selector(sortFoderButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *descAscButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    descAscButton.tag = 105;
    descAscButton.frame = CGRectMake(CGRectGetMaxX(segment.frame) + (itemWidth > 60 ? 13 : 8), 13, 24, 24);
    [descAscButton setImage:[NSBundle jk_imageWithName:@"file_sort_desc_off" type:@"png"] forState:(UIControlStateNormal)];
    [descAscButton setImage:[NSBundle jk_imageWithName:@"file_sort_desc_on" type:@"png"] forState:(UIControlStateSelected)];
    [sortWayContainerView addSubview:descAscButton];
    
    [descAscButton addTarget:self action:@selector(descAscButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 底部分隔线
    UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(catalogueLabel.frame) - 0.5, [UIScreen mainScreen].bounds.size.width, 0.3)];
    bottomLineView.backgroundColor = [UIColor colorWithRed:217.0/255.0 green:217.0/255.0 blue:217.0/255.0 alpha:1];
    [sectionHeader addSubview:bottomLineView];
    
    return catalogueLabel;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, 156);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, self.footerHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    JKFileExplorerItem *fileItem = [(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) objectAtIndex:indexPath.item];
    
    if (fileItem.showMoreAction || self.currentMoreAtionFileItem.showMoreAction) {
        
        JKFileExploreCollectionViewCell *cell = (JKFileExploreCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        [cell setHighlighted:NO];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isEditing) {
        
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        
        JKFileExplorerItem *fileItem = [(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) objectAtIndex:indexPath.item];
        
        fileItem.selected = !fileItem.selected;
        
        if (fileItem.isSelected) {
            
            [self.selectedFileItems addObject:fileItem];
            
        } else {
            
            if ([self.selectedFileItems containsObject:fileItem]) {
                
                [self.selectedFileItems removeObject:fileItem];
            }
        }
        
        !fileItem.fileInfoDidChange ? : fileItem.fileInfoDidChange(fileItem);
        
        if (self.selectedFileItems.count == (self.showSearchResult ? self.searchFileItemArr.count : self.fileItemArr.count)) {
            
            self.navigationItem.leftBarButtonItem.title = @"取消全选";
            
        } else {
            
            self.navigationItem.leftBarButtonItem.title = @"全选";
        }
        
        return;
    }
    
    [self refreshClearNewFileColor];
    
    if (self.currentMoreAtionFileItem.showMoreAction) {
        
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
        
        NSIndexPath *currentIndexPath = [NSIndexPath indexPathForItem:[(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) indexOfObject:self.currentMoreAtionFileItem] inSection:0];
        
        JKFileExploreCollectionViewCell *currentCell = (JKFileExploreCollectionViewCell *)[collectionView cellForItemAtIndexPath:currentIndexPath];
        
        [currentCell hideMoreActionContainerView];
        
        return;
    }
    
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    JKFileExplorerItem *fileItem = [(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) objectAtIndex:indexPath.item];
    
    JKFileExploreCollectionViewCell *cell = (JKFileExploreCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    if (fileItem.showMoreAction) {
        
        [cell hideMoreActionContainerView];
        
        return;
    }
    
    if (fileItem.isFolder) {
        
        [self pushToDirectoryWithFileViewItem:fileItem];
        
        return;
    }
    
    if ([[fileItem.fileSuffix lowercaseString] isEqualToString:@"zip"]) {
        
        [self unZipWithFileItem:fileItem];
        
        return;
    }
    
    if ([[fileItem.fileSuffix lowercaseString] isEqualToString:@"txt"]) {
        
        [self previewTextFileWithItem:fileItem];
        
        return;
    }
    
    /*
     if ([viewItem.fileSuffix isEqualToString:@"plist"] || [viewItem.fileSuffix isEqualToString:@"?"]) {
     
     _docVc = nil;
     
     _docVc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:viewItem.filePath]];
     _docVc.delegate = self;
     
     if ([_docVc presentPreviewAnimated:YES]){
     
     NSLog(@"打开成功");
     
     } else {
     
     NSLog(@"打开失败");
     
     JKFileExplorerWebViewController *vc = [JKFileExplorerWebViewController new];
     vc.data = [NSData dataWithContentsOfFile:viewItem.filePath];
     vc.navigationItem.title = viewItem.fileName;
     [self.navigationController pushViewController:vc animated:YES];
     }
     
     return;
     } //*/
    
    [self previewFileWithItem:fileItem];
}

#pragma mark
#pragma mark - 进入文件夹

- (void)pushToDirectoryWithFileViewItem:(JKFileExplorerItem *)fileItem{
    
    JKFileExplorerViewController *vc = [[JKFileExplorerViewController alloc] init];
    vc.sortConfig = _sortConfig;
    vc.arrangeType = _arrangeType;
    vc.fileItem = fileItem;
    vc->_operatingFileItems = _operatingFileItems;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    self.nextVC = vc;
}

#pragma mark
#pragma mark - 解压文件

- (void)unZipWithFileItem:(JKFileExplorerItem *)fileItem{
    
    JKCircularProgressView *circularProgressView = [[JKCircularProgressView alloc] initWithFrame:CGRectMake(110, 0, 70, 70)];
    
    circularProgressView.circleWidth = 2;
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 0)];
    [containerView addSubview:circularProgressView];
    
    JKAlertView *alertView = [JKAlertView alertViewWithTitle:[NSString stringWithFormat:@"解压文件\n%@", fileItem.fileName] message:nil style:(JKAlertStylePlain)];
    
    alertView.setDismissKey(@"JKFileExplorerUnZipKey");
    
#ifdef DEBUG
    alertView.enableDeallocLog(YES);
#endif
    
    alertView.setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
        
        return containerView;
    });
    
    JKAlertAction *cancelAction = [JKAlertAction actionWithTitle:@"取消" style:(JKAlertActionStyleCancel) handler:^(JKAlertAction *action) {
        
        if (circularProgressView.progress > 0) {
            return;
        }
        
        action.alertView.dismiss();
        
    }].setAutoDismiss(NO);
    
    [alertView addAction:cancelAction];
    
    //__weak typeof(cancelAction) weakCancelAction = cancelAction;
    
    [alertView addAction:[JKAlertAction actionWithTitle:@"确认" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
        if (circularProgressView.progress > 0) {
            return;
        }
        
        // 移除取消按钮
        cancelAction.setCustomView(^UIView *(JKAlertAction *action) {
            
            return [UIView new];
        });
        
        // 移除确认按钮
        action.setCustomView(^UIView *(JKAlertAction *action) {
            
            return [UIView new];
            
        }).setSeparatorLineHidden(YES);
        
        containerView.frame = CGRectMake(0, 0, 290, 90);
        
        action.alertView.resetAlertTitle([NSString stringWithFormat:@"正在解压...\n%@", fileItem.fileName]).resetOther().setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
            
            return containerView;
            
        }).setRelayoutComplete(^(JKAlertView *view) {
            
            // 清空一下block，不然会死循环
            view.setRelayoutComplete(nil);
            
            circularProgressView.progress = 0.01;
            
            [JKFileExplorerEngine unZipWithFileItem:fileItem progress:^(CGFloat progress) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    circularProgressView.progress = progress;
                });
                
            } complete:^(NSString *originalPath, NSString *unZippedPath, BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    circularProgressView.progress = 1;
                    
                    [self webUploader:nil didUploadFileAtPath:unZippedPath];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        action.alertView.resetAlertTitle([NSString stringWithFormat:@"解压完成\n%@", fileItem.fileName]).resetOther().addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:nil]).relayout(YES);
                    });
                    
                } else {
                    
                    [JKFileManager removeItemAtPath:unZippedPath];
                    
                    [self showStatusWithMessage:error.localizedDescription];
                    
                    action.alertView.resetAlertTitle([NSString stringWithFormat:@"解压失败\n%@", fileItem.fileName]).resetOther().setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
                        
                        return [UIView new];
                        
                    }).addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleCancel) handler:nil]).relayout(YES);
                }
            }];
        }).relayout(YES);
        
    }].setAutoDismiss(NO)];
    
    [alertView show];
}

#pragma mark
#pragma mark - 预览文件

- (void)previewFileWithItem:(JKFileExplorerItem *)fileItem{
    
    self.selectedFilePath = fileItem.filePath;
    
    self.navigationItem.backBarButtonItem = nil;
    
    NSArray *previewItemArr = @[];
    
    NSInteger index = 0;
    
    if (self.showSearchResult) {
        
        previewItemArr = self.searchFilePreviewItemArr;
        
        index = [self.searchFilePreviewItemArr indexOfObject:fileItem];
        
    } else {
        
        previewItemArr = self.filePreviewItemArr;
        
        index = [self.filePreviewItemArr indexOfObject:fileItem];
    }
    
    [JKFileExplorerPreviewController showWithPreviewItemList:previewItemArr index:index viewController:self];
}

#pragma mark
#pragma mark - 预览文本文件

- (void)previewTextFileWithItem:(JKFileExplorerItem *)fileItem{
    
    JKFileExplorerTextEditViewController *vc = [JKFileExplorerTextEditViewController new];
    
    vc.folderItem = self.fileItem;
    
    vc.filePath = fileItem.filePath;
    
    vc.navTitle = fileItem.fileName;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark
#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
    
    [self hideCellMoreActionContainerView];
    
    [self refreshClearNewFileColor];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (scrollView.contentOffset.y + scrollView.contentInset.top < 53) {
        
        [scrollView setContentOffset:CGPointMake(0, -scrollView.contentInset.top) animated:YES];
        
    } else if (scrollView.contentOffset.y + scrollView.contentInset.top < 106) {
        
        [scrollView setContentOffset:CGPointMake(0, -scrollView.contentInset.top + 106) animated:YES];
    }
}

#pragma mark
#pragma mark - 搜索

- (void)startSearchWithText:(NSString *)text{
    
    // 有错误，还搜个啥呀
    if (self.fileItem.fetchSubFileNameListError &&
        self.fileItemArr.count == 0) {
        
        return;
    }
    
    self.searchText = [text copy];
    
    [self.searchFileItemArr removeAllObjects];
    
    if (self.searchText == nil || [self.searchText isEqualToString:@""]) {
        
        self.showSearchResult = NO;
        
        [self.collectionView reloadData];
        
        return;
    }
    
    [self searchWithText:text];
}

- (void)searchWithText:(NSString *)text{
    
    [self.indicatorView startAnimating];
    
    dispatch_async([JKFileExplorerEngine explorerEngineQueue], ^{
        
        [self.searchFileItemArr removeAllObjects];
        [self.searchFilePreviewItemArr removeAllObjects];
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj.fileName.lowercaseString containsString:text.lowercaseString]) {
                
                [self.searchFileItemArr addObject:obj];
                
                if (!obj.isFolder) {
                    
                    [self.searchFilePreviewItemArr addObject:obj];
                }
            }
        }];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.indicatorView stopAnimating];
            
            self.showSearchResult = YES;
            
            [self.collectionView reloadData];
            
            [self adjustFooterHeight];
            
            if (self.fileNewItems.count > 0) {
                
                NSIndexPath *indexPathNew = nil;
                
                if ([self.fileItemArr containsObject:self.fileNewItems.firstObject]) {
                    
                    NSInteger index = [self.fileItemArr indexOfObject:self.fileNewItems.firstObject];
                    
                    indexPathNew = [NSIndexPath indexPathForItem:index inSection:0];
                }
                
                if (indexPathNew) {
                    
                    [self.collectionView scrollToItemAtIndexPath:indexPathNew atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
                }
                
            } else {
                
                //[self adjustCollectionContentOffset];
            }
            
            self.tipLabel.text = self.fileItem.fetchSubFileNameListError ? self.fileItem.subTotalCountString : @"no result";
            self.tipLabel.hidden = (self.searchFileItemArr.count > 0);
        });
    });
}

- (void)cancelSeach{
    
    self.searchText = nil;
    
    [self.searchFileItemArr removeAllObjects];
    
    self.showSearchResult = NO;
    
    [self.collectionView reloadData];
    
    self.tipLabel.text = self.fileItem.fetchSubFileNameListError ? self.fileItem.subTotalCountString : @"empty";
    self.tipLabel.hidden = (self.fileItemArr.count > 0);
}

#pragma mark
#pragma mark - UISearchBarDelegate

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    NSLog(@"searchBarTextDidEndEditing");
    
    if (searchBar.text.length > 0) { return; }
    
    [self cancelSeach];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    if (searchBar.text.length <= 0) { return; }
    
    [searchBar resignFirstResponder];
    
    [self startSearchWithText:searchBar.text];
}

#pragma mark
#pragma mark - 处理cell点击

- (void)solveCellClick:(JKFileExploreCollectionViewCell *)cell{
    
    __weak typeof(self) weakSelf = self;
    
    if (!cell.infoButtonClickBlock) {
        
        [cell setInfoButtonClickBlock:^(JKFileExplorerItem *fileItem) {
            
            [weakSelf clickFileInfoWithFileItem:fileItem];
        }];
    }
    
    if (!cell.moreActionWillShowClickBlock) {
        
        [cell setMoreActionWillShowClickBlock:^(JKFileExplorerItem *fileItem) {
            
            if (weakSelf.currentMoreAtionFileItem == fileItem) { return; }
            
            [weakSelf hideCellMoreActionContainerView];
            
            weakSelf.currentMoreAtionFileItem = fileItem;
        }];
    }
    
    if (!cell.moreButtonClickBlock) {
        
        [cell setMoreButtonClickBlock:^(JKFileExplorerItem *fileItem) {
            
            [weakSelf clickFileInfoWithFileItem:fileItem];
        }];
    }
    
    if (!cell.deleteButtonClickBlock) {
        
        [cell setDeleteButtonClickBlock:^(JKFileExplorerItem *fileItem) {
            
            [weakSelf deleteFileItem:fileItem];
        }];
    }
}

#pragma mark
#pragma mark - 点击文件info弹出sheet

- (void)clickFileInfoWithFileItem:(JKFileExplorerItem *)fileItem{
    
    [self showFileItemInfo:fileItem];
}

- (void)showFileItemInfo:(JKFileExplorerItem *)fileItem{
    
    NSString *message = fileItem.isFolder ? fileItem.subTotalCountString : fileItem.fileSizeString;
    
    if (fileItem.creationDateString) {
        
        message = [[[message stringByAppendingString:@"\n"] stringByAppendingString:fileItem.creationDateString] stringByAppendingString:@" 创建"];
    }
    
    if (fileItem.modificationDateString) {
        
        message = [[[message stringByAppendingString:@"\n"] stringByAppendingString:fileItem.modificationDateString] stringByAppendingString:@" 修改"];
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:fileItem.fileName message:message preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    if (fileItem.fileAttributeError || fileItem.fetchSubFileNameListError) { // 无权限
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        
        [self presentViewController:alertVc animated:YES completion:nil];
        
        return;
    }
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"分享" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (fileItem) {
            
            [self shareWithFileItems:@[fileItem]];
        }
    }]];
    
    if (fileItem != self.fileItem && fileItem.deletable) {
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"重命名" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [self showTextfieldAlertWithTitle:@"重命名" message:fileItem.fileName text:fileItem.fileName placeholder:@"新名称" verifyTitle:@"重命名" verifyAction:^(NSString *text) {
                
                [self renameWithfileItem:fileItem name:text];
            }];
        }]];
    }
    
    if (fileItem.deletable) {
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"移动" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [self moveFileItem:fileItem];
        }]];
    }
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"复制" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self copyFileItem:fileItem];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"压缩" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self zipWithFileItem:fileItem];
    }]];
    
    if (fileItem.deletable) {
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
            
            [self deleteFileItem:fileItem];
        }]];
    }
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark 分享文件

- (void)shareWithFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    if (!fileItems || fileItems.count <= 0) { return; }
    
    NSMutableArray *URLArr = [NSMutableArray array];
    
    for (JKFileExplorerItem *fileItem in fileItems) {
        
        NSURL *URL = [NSURL fileURLWithPath:fileItem.filePath];
        
        if (URL) {
            
            [URLArr addObject:URL];
        }
    }
    
    [JKFileExplorerAirDropShareManager shareWithViewController:self URLArray:URLArr];
}

#pragma mark 重命名

- (void)renameWithfileItem:(JKFileExplorerItem *)fileItem name:(NSString *)name{
    
    if ([name isEqualToString:fileItem.fileName]) { return; }
    
    NSString *path = [self.fileItem.filePath stringByAppendingPathComponent:name];
    
    if ([self.filePathItemDict objectForKey:path]) {
        
        NSLog(@"重命名失败: 文件已存在");
        
        [self showStatusWithMessage:@"重命名失败: 文件已存在"];
        
        return;
    }
    
    NSError *error;
    
    BOOL success = [JKFileManager moveItemAtPath:fileItem.filePath toPath:path error:&error];
    
    if (error) {
        
        NSLog(@"重命名失败: %@", error.localizedDescription);
        
        [self showStatusWithMessage:@"重命名失败: 权限受限"];
        
        return;
    }
    
    if (success && [JKFileManager isExistsAtPath:path]) {
        
        [self postNotificationOfDeleteFilePath:fileItem.filePath];
        
        [self postNotificationOfAddFilePath:path];
        
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.fileItem.subFileNameList];
        
        [arrM removeObject:fileItem.fileName];
        
        [arrM addObject:name];
        
        self.fileItem.subFileNameList = arrM;
        
        NSLog(@"重命名成功: %@", path);
        
        // 移除缓存
        [self.filePathItemDict removeObjectForKey:fileItem.filePath];
        
        fileItem.fileName = name;
        fileItem.filePath = path;
        
        // 添加缓存
        [self.filePathItemDict setObject:fileItem forKey:fileItem.filePath];
        
        fileItem.isNew = YES;
        
        [self.fileNewItems addObject:fileItem];
        
        [self resort];
    }
}

#pragma mark 移动/复制

- (void)moveFileItem:(JKFileExplorerItem *)fileItem{
    
    if (!fileItem) { return; }
    
    [self postWillOperateFileNotificationWithItems:@[fileItem] operateType:(JKFileExplorerFileOperateTypeMove)];
}

- (void)copyFileItem:(JKFileExplorerItem *)fileItem{
    
    if (!fileItem) { return; }
    
    [self postWillOperateFileNotificationWithItems:@[fileItem] operateType:(JKFileExplorerFileOperateTypeCopy)];
}

#pragma mark 压缩

- (void)zipWithFileItem:(JKFileExplorerItem *)fileItem{
    
    JKCircularProgressView *circularProgressView = [[JKCircularProgressView alloc] initWithFrame:CGRectMake(110, 0, 70, 70)];
    
    circularProgressView.circleWidth = 2;
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 0)];
    [containerView addSubview:circularProgressView];
    
    JKAlertView *alertView = [JKAlertView alertViewWithTitle:[NSString stringWithFormat:@"压缩\n%@", fileItem.fileName] message:nil style:(JKAlertStylePlain)];
    
    alertView.setDismissKey(@"JKFileExplorerZipKey");
    
#ifdef DEBUG
    alertView.enableDeallocLog(YES);
#endif
    
    alertView.setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
        
        return containerView;
    });
    
    JKAlertAction *cancelAction = [JKAlertAction actionWithTitle:@"取消" style:(JKAlertActionStyleCancel) handler:^(JKAlertAction *action) {
        
        if (circularProgressView.progress > 0) {
            return;
        }
        
        action.alertView.dismiss();
        
    }].setAutoDismiss(NO);
    
    [alertView addAction:cancelAction];
    
    //__weak typeof(cancelAction) weakCancelAction = cancelAction;
    
    [alertView addAction:[JKAlertAction actionWithTitle:@"确认" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
        if (circularProgressView.progress > 0) {
            return;
        }
        
        // 移除取消按钮
        cancelAction.setCustomView(^UIView *(JKAlertAction *action) {
            
            return [UIView new];
        });
        
        // 移除确认按钮
        action.setCustomView(^UIView *(JKAlertAction *action) {
            
            return [UIView new];
            
        }).setSeparatorLineHidden(YES);
        
        containerView.frame = CGRectMake(0, 0, 290, 90);
        
        action.alertView.resetAlertTitle([NSString stringWithFormat:@"正在压缩...\n%@", fileItem.fileName]).resetOther().setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
            
            return containerView;
            
        }).setRelayoutComplete(^(JKAlertView *view) {
            
            // 清空一下block，不然会死循环
            view.setRelayoutComplete(nil);
            
            if (!fileItem.isFolder) {
                
                circularProgressView.progress = 0.2;
            }
            
            [JKFileExplorerEngine zipWithFileItem:fileItem password:nil progress:^(CGFloat progress) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    circularProgressView.progress = progress;
                });
                
            } complete:^(NSString *originalPath, NSString *zippedPath, BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    circularProgressView.progress = 1;
                    
                    [self webUploader:nil didUploadFileAtPath:zippedPath];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        action.alertView.resetAlertTitle([NSString stringWithFormat:@"压缩完成\n%@", fileItem.fileName]).resetOther().addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:nil]).relayout(YES);
                    });
                    
                } else {
                    
                    [JKFileManager removeItemAtPath:zippedPath];
                    
                    [self showStatusWithMessage:error.localizedDescription];
                    
                    action.alertView.resetAlertTitle([NSString stringWithFormat:@"压缩失败\n%@", fileItem.fileName]).resetOther().setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
                        
                        return [UIView new];
                        
                    }).addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleCancel) handler:nil]).relayout(YES);
                }
            }];
            
        }).relayout(YES);
        
    }].setAutoDismiss(NO)];
    
    [alertView show];
}

#pragma mark 删除

- (void)deleteFileItem:(JKFileExplorerItem *)fileItem{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:fileItem.fileName message:fileItem.isFolder ? @"确定要删除此文件夹" : @"确定要删除此文件？" preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"执行删除文件navigationController-->%@", self.navigationController);
        
        NSError *error;
        
        BOOL success = [JKFileManager removeItemAtPath:fileItem.filePath error:&error];
        
        if (error) {
            
            NSLog(@"删除文件失败: %@", error.localizedDescription);
            
            [self showStatusWithMessage:@"删除文件失败!"];
            
            return;
        }
        
        if (success && ![JKFileManager isExistsAtPath:fileItem.filePath]) {
            
            [self postNotificationOfDeleteFilePath:fileItem.filePath];
            
            NSLog(@"删除文件成功: %@", fileItem.filePath);
            
            [self refreshForDeleteFileWithPath:fileItem.filePath autoReload:YES];
        }
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark
#pragma mark - 文件更新

/// 更新文件新增
- (void)refreshForNewFileWithPath:(NSString *)path
                       autoResort:(BOOL)autoResort
                         complete:(void(^)(JKFileExplorerItem *fileItem))complete{
    
    if (![JKFileManager isExistsAtPath:path]) { return; }
    
    [JKFileExplorerEngine fetchFileItemWithDirectoryPath:path finish:^(NSString *directoryPath, JKFileExplorerItem *fileItem) {
        
        JKFileExplorerItem *item = [self.filePathItemDict objectForKey:path];
        
        if (item) {
            
            [self.filePathItemDict setObject:item forKey:path];
            
            if ([self.fileItemArr containsObject:item]) {
                
                NSInteger index = [self.fileItemArr indexOfObject:item];
                
                [self.fileItemArr replaceObjectAtIndex:index withObject:fileItem];
            }
            
            if ([self.searchFileItemArr containsObject:item]) {
                
                NSInteger index = [self.searchFileItemArr indexOfObject:item];
                
                [self.searchFileItemArr replaceObjectAtIndex:index withObject:fileItem];
            }
            
            fileItem.fileInfoDidChange = item.fileInfoDidChange;
            
            !fileItem.fileInfoDidChange ? : fileItem.fileInfoDidChange(fileItem);
            
            return;
        }
        
        [self.fileItemArr addObject:fileItem];
        
        [self.filePathItemDict setObject:fileItem forKey:fileItem.filePath];
        
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.fileItem.subFileNameList];
        [arrM addObject:fileItem.fileName];
        
        fileItem.isNew = YES;
        
        [self.fileNewItems addObject:fileItem];
        
        if (fileItem.isFolder) {
            
            fileItem.subFolderCount += 1;
            
            [JKFileExplorerEngine fetchFileNameListWithFileItem:fileItem success:^(JKFileExplorerItem *fileItem, NSArray<NSString *> *fileNameList) {
                
                if (autoResort) {
                    
                    [self resort];
                }
                
                !complete ? : complete(fileItem);
                
            } failure:^(NSError *error) {
                
                if (autoResort) {
                    
                    [self resort];
                }
                
                !complete ? : complete(fileItem);
            }];
            
        } else {
            
            fileItem.subFileCount += 1;
            
            if (autoResort) {
                
                [self resort];
            }
            
            !complete ? : complete(fileItem);
        }
        
        self.fileItem.subFileNameList = arrM;
        
        !self.fileItem.fileInfoDidChange ? : self.fileItem.fileInfoDidChange(self.fileItem);
    }];
}

/// 更新文件移除
- (void)refreshForDeleteFileWithPath:(NSString *)path autoReload:(BOOL)autoReload{
    
    if ([JKFileManager isExistsAtPath:path]) { return; }
    
    __block JKFileExplorerItem *fileItem = [self.filePathItemDict objectForKey:path];
    
    if (!fileItem) {
        
        [self.fileItemArr enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([obj.filePath isEqualToString:path]) {
                
                fileItem = obj;
                
                *stop = YES;
            }
        }];
        
    } else {
        
        [self.filePathItemDict removeObjectForKey:path];
    }
    
    if (!fileItem) { return; }
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.fileItem.subFileNameList];
    
    [arrM removeObject:fileItem.fileName];
    
    self.fileItem.subFileNameList = arrM;
    
    if (fileItem.isFolder) {
        
        self.fileItem.subFolderCount -= 1;
        
    } else {
        
        self.fileItem.subFileCount -= 1;
    }
    
    !self.fileItem.fileInfoDidChange ? : self.fileItem.fileInfoDidChange(self.fileItem);
    
    if (!autoReload) {
        
        if ([self.fileItemArr containsObject:fileItem]) {
            
            [self.fileItemArr removeObject:fileItem];
        }
        
        if ([self.searchFileItemArr containsObject:fileItem]) {
            
            [self.searchFileItemArr removeObject:fileItem];
        }
        
        return;
    }
    
    NSInteger index = [(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) indexOfObject:fileItem];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    if ([self.fileItemArr containsObject:fileItem]) {
        
        [self.fileItemArr removeObject:fileItem];
    }
    
    if ([self.searchFileItemArr containsObject:fileItem]) {
        
        [self.searchFileItemArr removeObject:fileItem];
    }
    
    [self checkDiskSize];
    
    [self.collectionView performBatchUpdates:^{
        
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        
    } completion:^(BOOL finished) {
        
        [self adjustFooterHeight];
        
        [self.collectionView reloadData];
    }];
}

#pragma mark
#pragma mark - 点击加号弹出当前文件夹内操作sheet

- (void)addButtonClick:(UIButton *)button{
    
    if (self.isEditing) {
        
        [self showEdtingSheet];
        
        return;
    }
    
    if (self.wifiTransferAddress) {
        
        [self stopWifiTransfer];
        
        return;
    }
    
    [self showNormalSheet];
}

#pragma mark
#pragma mark - 编辑模式

- (void)showEdtingSheet{
    
    NSInteger count = self.selectedFileItems.count;
    
    if (count == 0) {
        
        [self showStatusWithMessage:@"请选择要操作的文件~"];
        
        return;
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"已选择%zd项", self.selectedFileItems.count] message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"分享" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self shareWithFileItems:self.selectedFileItems];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"压缩" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        JKFileExplorerItem *firstItem = self.selectedFileItems.firstObject;
        
        if (count == 1) {
            
            [self zipWithFileItem:firstItem];
            
            [self exitEditingMode];
            
        } else {
            
            [self showTextfieldAlertWithTitle:@"压缩文件" message:[NSString stringWithFormat:@"%@等%zd个文件", firstItem.fileName, count] text:nil placeholder:@"请输入文件名" verifyTitle:@"压缩" verifyAction:^(NSString *text) {
                
                [self multiZipWithFileItems:self.selectedFileItems zipFileName:text password:nil];
                
                [self exitEditingMode];
            }];
        }
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"移动" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self multiMoveFileItems:self.selectedFileItems];
        
        [self exitEditingMode];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"复制" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self multiCopyFileItems:self.selectedFileItems];
        
        [self exitEditingMode];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        [self multiDeleteFileItems:self.selectedFileItems];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark 批量压缩

- (void)multiZipWithFileItems:(NSArray <JKFileExplorerItem *> *)fileItems
                  zipFileName:(NSString *)zipFileName
                     password:(NSString *)password{
    
    if (!fileItems || !zipFileName) { return; }
    
    NSInteger count = fileItems.count;
    
    JKCircularProgressView *circularProgressView = [[JKCircularProgressView alloc] initWithFrame:CGRectMake(110, 0, 70, 70)];
    
    circularProgressView.circleWidth = 2;
    circularProgressView.progress = 0.2;
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 90)];
    [containerView addSubview:circularProgressView];
    
    JKAlertView *alertView = [JKAlertView alertViewWithTitle:[NSString stringWithFormat:@"正在压缩%zd个文件...", count] message:nil style:(JKAlertStylePlain)];
    
    alertView.setDismissKey(@"JKFileExplorerMultiZipKey");
    
#ifdef DEBUG
    alertView.enableDeallocLog(YES);
#endif
    
    alertView.setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
        
        return containerView;
    });
    
    alertView.addAction([JKAlertAction actionWithTitle:nil style:(JKAlertActionStyleCancel) handler:nil].setAutoDismiss(NO).setCustomView(^UIView *(JKAlertAction *action) {
        
        return [UIView new];
        
    }).setSeparatorLineHidden(YES));
    
    JKAlertAction *cancelAction = [JKAlertAction actionWithTitle:nil style:(JKAlertActionStyleCancel) handler:nil].setAutoDismiss(NO).setCustomView(^UIView *(JKAlertAction *action) {
        
        return [UIView new];
        
    }).setSeparatorLineHidden(YES);
    
    [alertView addAction:cancelAction];
    
    alertView.show();
    
    NSString *zipFilePath = [[self.fileItem.filePath stringByAppendingPathComponent:zipFileName] stringByAppendingString:@".zip"];
    
    [JKFileExplorerEngine multiZipWithFileItems:fileItems zipFilePath:zipFilePath password:password progress:^(CGFloat progress) {
        
    } complete:^(NSString *zippedPath, BOOL succeeded, NSError * _Nullable error) {
        
        if (succeeded) {
            
            circularProgressView.progress = 1;
            
            [self webUploader:nil didUploadFileAtPath:zippedPath];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                cancelAction.alertView.resetAlertTitle([NSString stringWithFormat:@"压缩完成\n%@", zippedPath.lastPathComponent]).resetOther().addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:nil]).relayout(YES);
            });
            
        } else {
            
            [JKFileManager removeItemAtPath:zippedPath];
            
            [self showStatusWithMessage:error.localizedDescription];
            
            cancelAction.alertView.resetAlertTitle([NSString stringWithFormat:@"压缩失败\n%@", zippedPath.lastPathComponent]).resetOther().setCustomPlainTitleView(YES, ^UIView *(JKAlertView *view) {
                
                return [UIView new];
                
            }).addAction([JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleCancel) handler:nil]).relayout(YES);
        }
    }];
}

#pragma mark 批量移动

- (void)multiMoveFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
     
    [self postWillOperateFileNotificationWithItems:fileItems operateType:(JKFileExplorerFileOperateTypeMove)];
}

#pragma mark 批量复制

- (void)multiCopyFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    [self postWillOperateFileNotificationWithItems:fileItems operateType:(JKFileExplorerFileOperateTypeCopy)];
}

#pragma mark 批量删除

- (void)multiDeleteFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"删除文件" message:[NSString stringWithFormat:@"确定要删除%zd项文件？", fileItems.count] preferredStyle:(UIAlertControllerStyleAlert)];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        
        [self verifyMultiDeleteFileItems:fileItems];
        
        [self exitEditingMode];
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)verifyMultiDeleteFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    NSError *error = nil;
    
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.fileItem.subFileNameList];
    
    for (JKFileExplorerItem *item in fileItems) {
        
        BOOL success = [JKFileManager removeItemAtPath:item.filePath error:&error];
        
        if (success) {
            
            JKFileExplorerItem *fileItem = [self.filePathItemDict objectForKey:item.filePath];
            
            if (fileItem) {
                
                [self.filePathItemDict removeObjectForKey:item.filePath];
                
            } else {
                
                fileItem = item;
            }
            
            if (self.showSearchResult) {
                
                if ([self.searchFileItemArr containsObject:fileItem]) {
                    
                    [self.searchFileItemArr removeObject:fileItem];
                }
            }
            
            if ([self.fileItemArr containsObject:fileItem]) {
                
                [self.fileItemArr removeObject:fileItem];
            }
            
            [arrM removeObject:fileItem.fileName];
            
            if (fileItem.isFolder) {
                
                self.fileItem.subFolderCount -= 1;
                
            } else {
                
                self.fileItem.subFileCount -= 1;
            }
        }
    }
    
    self.fileItem.subFileNameList = arrM;
    
    !self.fileItem.fileInfoDidChange ? : self.fileItem.fileInfoDidChange(self.fileItem);
    
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    
    [self adjustFooterHeight];
    
    [self checkDiskSize];
    
    if (self.showSearchResult) {
        
        [self searchWithText:self.searchText];
    }
}

#pragma mark
#pragma mark - 正常情况

- (void)showNormalSheet{
    
    NSString *message = self.fileItem.subTotalCountString;
    
    if (self.fileItem.creationDateString) {
        
        message = [[[message stringByAppendingString:@"\n"] stringByAppendingString:self.fileItem.creationDateString] stringByAppendingString:@" 创建"];
    }
    
    if (self.fileItem.modificationDateString) {
        
        message = [[[message stringByAppendingString:@"\n"] stringByAppendingString:self.fileItem.modificationDateString] stringByAppendingString:@" 修改"];
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:self.fileItem.fileName message:message preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    if (self.fileItem.fetchSubFileNameListError) { // 无权限
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        
        [self presentViewController:alertVc animated:YES completion:nil];
        
        return;
    }
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"新建下载" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self showDownloadFileAlert];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"下载列表" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self pushToDownloadTaskList];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"新建文件夹" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self showTextfieldAlertWithTitle:@"新建文件夹" message:nil text:nil placeholder:@"文件夹名称" verifyTitle:@"创建" verifyAction:^(NSString *text) {
            
            [self createFolderWithName:text];
        }];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"新建文件" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self showTextfieldAlertWithTitle:@"新建文件" message:nil text:nil placeholder:@"文件名称" verifyTitle:@"创建" verifyAction:^(NSString *text) {
            
            [self createFileWithName:text];
        }];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"WiFi传输" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self transferFileViaWifi];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"iCloud云盘" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        [self showiCloudFiles];
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"分享此文件夹" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (self.fileItem) {
            
            [self shareWithFileItems:@[self.fileItem]];
        }
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark 新建下载

- (void)showDownloadFileAlert{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"下载文件" message:@"请输入下载链接，文件名将自动匹配，也可手动修改" preferredStyle:(UIAlertControllerStyleAlert)];
    
    __block UITextField *urlTextField;
    __block UITextField *fileNameTextField;
    
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        urlTextField = textField;
        
        textField.placeholder = @"链接地址";
    }];
    
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        fileNameTextField = textField;
        
        textField.placeholder = @"文件名";
    }];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"开始下载" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (!urlTextField.hasText) { return; }
        
        NSString *fileName = fileNameTextField.text;
        
        if (!fileNameTextField.hasText) {
            
            fileName = [urlTextField.text lastPathComponent];
        }
        
        fileName = [[JKFileExplorerEngine checkDuplicationNameWithFilePath:[self.fileItem.filePath stringByAppendingPathComponent:fileName] isFolder:NO] lastPathComponent];
        
        fileNameTextField.text = fileName;
        
        [self startDownloadWithUrl:urlTextField.text fileName:fileName];
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
    
    [urlTextField addTarget:self action:@selector(urlTextFieldEditingChanged:) forControlEvents:(UIControlEventEditingChanged)];
    
    self.fileNameTextField = fileNameTextField;
}

- (void)urlTextFieldEditingChanged:(UITextField *)textField{
    
    if (![self.fileNameTextField isKindOfClass:[UITextField class]]) {
        return;
    }
    
    if (self.fileNameTextField.hasText) {
        return;
    }
    
    if (textField.text.length > 8) {
        
        NSString *url = textField.text;
        
        if ([url containsString:@"?"]) {
            
            url = [[url componentsSeparatedByString:@"?"] firstObject];
        }
        
        self.fileNameTextField.text = [url lastPathComponent];
    }
}

- (void)startDownloadWithUrl:(NSString *)url fileName:(NSString *)fileName{
    
    if (!url || !fileName) { return; }
    
    JKFileExplorerDownloadTaskViewController *vc = [JKFileExplorerDownloadTaskViewController addTaskWithUrl:url directory:self.fileItem.filePath fileName:fileName];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 下载列表

- (void)pushToDownloadTaskList{
    
    JKFileExplorerDownloadTaskViewController *vc = [JKFileExplorerDownloadTaskViewController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 新建文件夹

- (void)createFolderWithName:(NSString *)folderName{
    
    NSString *path = [self.fileItem.filePath stringByAppendingPathComponent:folderName];
    
    NSError *error;
    
    BOOL success = [JKFileManager createDirectoryAtPath:path error:&error];
    
    if (error) {
        
        NSLog(@"创建文件夹失败: %@", error.localizedDescription);
        
        return;
    }
    
    if (success) {
        
        [self postNotificationOfAddFilePath:path];
        
        NSLog(@"创建文件夹成功: %@", path);
        
        [self refreshForNewFileWithPath:path autoResort:YES complete:nil];
    }
}

#pragma mark 新建文件

- (void)createFileWithName:(NSString *)folderName{
    
    if (!folderName) { return; }
    
    JKFileExplorerTextEditViewController *vc = [JKFileExplorerTextEditViewController new];
    
    vc.isCreateNewFile = YES;
    
    vc.navTitle = folderName;
    
    vc.folderItem = self.fileItem;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark WiFi传输

- (void)transferFileViaWifi{
    
    [self startWifiTransfer];
}

#pragma mark 浏览iCloud云盘文件

- (void)showiCloudFiles{
    
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.item"] inMode:(UIDocumentPickerModeOpen)];
    
    documentPicker.delegate = self;
    
    [self presentViewController:documentPicker animated:YES completion:nil];
}

#pragma mark
#pragma mark - 处理WiFi传文件

- (void)startWifiTransfer{
    
    if (self.wifiTransferAddress) {
        
        [self showStatusWithMessage:@"WiFi传输已开启！"];
        
        return;
    }
    
    [JKWebServerManager startWithUploadDirectoryPath:self.fileItem.filePath delegate:self config:^(JKWebServerManager *manager) {
        
    } success:^(NSString *url, NSString *IP, NSUInteger port) {
        
        self.wifiTransferAddress = url;
        
        self.wifiTransferButton.hidden = NO;
        
        self.selectButton.hidden = YES;
        
        [self.wifiTransferButton setTitle:[NSString stringWithFormat:@"请在PC浏览器输入以下地址\n%@\n点击可复制该地址", self.wifiTransferAddress] forState:(UIControlStateNormal)];
        
        [UIView animateWithDuration:0.25 animations:^{
            
            self.addButton.transform = CGAffineTransformMakeRotation(M_PI_4);
        }];
        
    } failure:^(NSError *error) {
        
        [self showStatusWithMessage:@"WiFi传输开启失败！请检查WiFi是否已连接。"];
        
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)stopWifiTransfer{
    
    [JKWebServerManager stop];
    
    if (self.selectedFileItems.count <= 0) {
        
        self.selectButton.hidden = NO;
    }
    
    self.wifiTransferButton.hidden = YES;
    [self.wifiTransferButton setTitle:@"" forState:(UIControlStateNormal)];
    
    self.wifiTransferAddress = nil;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.addButton.transform = CGAffineTransformIdentity;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)wifiTransferInfoButtonClick:(UIButton *)button{
    
    UIPasteboard *pastBoard = [UIPasteboard generalPasteboard];
    pastBoard.string = self.wifiTransferAddress;
    
    [self showStatusWithMessage:@"复制成功！"];
}

#pragma mark
#pragma mark - GCDWebUploaderDelegate

/**
 *  This method is called whenever a file has been downloaded.
 */
- (void)webUploader:(GCDWebUploader *)uploader didDownloadFileAtPath:(NSString*)path{
    
}

/**
 *  This method is called whenever a file has been uploaded.
 */
- (void)webUploader:(GCDWebUploader *)uploader didUploadFileAtPath:(NSString *)path{
    
    [self solveNewFileDidRecieveWithPath:path];
    
    [self postNotificationOfAddFilePath:path];
}

/**
 *  This method is called whenever a file or directory has been moved.
 */
- (void)webUploader:(GCDWebUploader *)uploader didMoveItemFromPath:(NSString *)fromPath toPath:(NSString *)toPath{
    
    JKFileExplorerItem *fromItem = [self.filePathItemDict objectForKey:fromPath];
    
    if (fromItem) { // 从当前文件夹移除
        
        [self refreshForDeleteFileWithPath:fromPath autoReload:YES];
        
    } else { // 从当前文件夹的子文件夹中移除
        
        NSString *fromPathDirectory = [fromPath stringByDeletingLastPathComponent];
        
        fromItem = [self.filePathItemDict objectForKey:fromPathDirectory];
        
        if (fromItem) { // 是直接子文件夹
            
            NSMutableArray *arrM = [NSMutableArray array];
            
            [arrM addObjectsFromArray:fromItem.subFileNameList];
            
            [arrM removeObject:[fromPath lastPathComponent]];
            
            fromItem.subFileNameList = arrM;
            
            !fromItem.fileInfoDidChange ? : fromItem.fileInfoDidChange(fromItem);
        }
        
        // 次级子文件夹不再处理
    }
    
    [self postNotificationOfDeleteFilePath:fromItem.filePath];
    
    NSString *toPathDirectory = [toPath stringByDeletingLastPathComponent];
    
    if ([toPathDirectory isEqualToString:self.fileItem.filePath]) { // 移动到当前文件夹
        
        [self refreshForNewFileWithPath:toPath autoResort:YES complete:nil];
        
    } else { // 移动到当前文件夹的子文件夹
        
        JKFileExplorerItem *toItem = [self.filePathItemDict objectForKey:toPathDirectory];
        
        if (toItem) { // 是直接子文件夹
            
            NSMutableArray *arrM = [NSMutableArray array];
            
            [arrM addObjectsFromArray:toItem.subFileNameList];
            
            [arrM addObject:[toPath lastPathComponent]];
            
            toItem.subFileNameList = arrM;
            
            !toItem.fileInfoDidChange ? : toItem.fileInfoDidChange(toItem);
        }
        
        // 次级子文件夹不再处理
    }
    
    [self postNotificationOfAddFilePath:toPath];
}

/**
 *  This method is called whenever a file or directory has been deleted.
 */
- (void)webUploader:(GCDWebUploader *)uploader didDeleteItemAtPath:(NSString*)path{
    
    JKFileExplorerItem *item = [self.filePathItemDict objectForKey:path];
    
    if (item) { // 移除的是当前文件夹下子文件
        
        [self refreshForDeleteFileWithPath:path autoReload:YES];
        
    } else { // 移除的是当前文件夹下子文件夹中文件
        
        NSString *directory = [path stringByDeletingLastPathComponent];
        
        JKFileExplorerItem *subItem = [self.filePathItemDict objectForKey:directory];
        
        if (subItem) { // 直接的子文件夹
            
            NSMutableArray *arrM = [NSMutableArray array];
            
            [arrM addObjectsFromArray:subItem.subFileNameList];
            
            [arrM removeObject:[path lastPathComponent]];
            
            subItem.subFileNameList = arrM;
            
            !subItem.fileInfoDidChange ? : subItem.fileInfoDidChange(subItem);
        }
        
        // 次级文件夹不再处理
    }
    
    [self postNotificationOfDeleteFilePath:path];
}

/**
 *  This method is called whenever a directory has been created.
 */
- (void)webUploader:(GCDWebUploader *)uploader didCreateDirectoryAtPath:(NSString*)path{
    
    [self solveNewFileDidRecieveWithPath:path];
}

/// 处理接收到新文件/创建新文件夹
- (void)solveNewFileDidRecieveWithPath:(NSString *)path{
    
    // 获取目录路径
    NSString *directory = [path stringByDeletingLastPathComponent];
    
    if ([directory isEqualToString:self.fileItem.filePath]) { // 当前文件夹接收到新文件
        
        [self refreshForNewFileWithPath:path autoResort:YES complete:nil];
        
    } else { // 当前文件夹下子文件夹接收到新文件
        
        JKFileExplorerItem *subItem = [self.filePathItemDict objectForKey:directory];
        
        if (subItem) { // 直接的子文件夹
            
            NSMutableArray *arrM = [NSMutableArray array];
            
            [arrM addObjectsFromArray:subItem.subFileNameList];
            
            [arrM addObject:[path lastPathComponent]];
            
            subItem.subFileNameList = arrM;
            
            !subItem.fileInfoDidChange ? : subItem.fileInfoDidChange(subItem);
        }
        
        // 次级文件夹不再处理
    }
}

#pragma mark
#pragma mark - GCDWebServerDelegate

/**
 *  This method is called after the server has successfully started.
 */
- (void)webServerDidStart:(GCDWebServer*)server{
    
}

/**
 *  This method is called after the Bonjour registration for the server has
 *  successfully completed.
 *
 *  Use the "bonjourServerURL" property to retrieve the Bonjour address of the
 *  server.
 */
- (void)webServerDidCompleteBonjourRegistration:(GCDWebServer*)server{
    
}

/**
 *  This method is called after the NAT port mapping for the server has been
 *  updated.
 *
 *  Use the "publicServerURL" property to retrieve the public address of the
 *  server.
 */
- (void)webServerDidUpdateNATPortMapping:(GCDWebServer*)server{
    
}

/**
 *  This method is called when the first GCDWebServerConnection is opened by the
 *  server to serve a series of HTTP requests.
 *
 *  A series of HTTP requests is considered ongoing as long as new HTTP requests
 *  keep coming (and new GCDWebServerConnection instances keep being opened),
 *  until before the last HTTP request has been responded to (and the
 *  corresponding last GCDWebServerConnection closed).
 */
- (void)webServerDidConnect:(GCDWebServer*)server{
    
}

/**
 *  This method is called when the last GCDWebServerConnection is closed after
 *  the server has served a series of HTTP requests.
 *
 *  The GCDWebServerOption_ConnectedStateCoalescingInterval option can be used
 *  to have the server wait some extra delay before considering that the series
 *  of HTTP requests has ended (in case there some latency between consecutive
 *  requests). This effectively coalesces the calls to -webServerDidConnect:
 *  and -webServerDidDisconnect:.
 */
- (void)webServerDidDisconnect:(GCDWebServer*)server{
    
}

/**
 *  This method is called after the server has stopped.
 */
- (void)webServerDidStop:(GCDWebServer*)server{
    
    [self stopWifiTransfer];
}

#pragma mark
#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls{
    
    NSLog(@"didPickDocumentsAtURLs: %@", urls);
    
    //获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    
    if (fileUrlAuthozied) {
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            
            //读取文件
            //NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            
            if (error) {
                // 读取出错
            } else {
                // 上传
                //[self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
                
                [self.indicatorView startAnimating];
                
                NSString *filePath = [newURL path];
                
                NSString *toPath = [self.fileItem.filePath stringByAppendingPathComponent:[filePath lastPathComponent]];
                
                // 保存文件
                [JKFileExplorerEngine saveData:fileData toPath:toPath success:^(NSString *destinationPath) { // 保存成功
                    
                    [self.indicatorView stopAnimating];
                    
                    [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCopySuccess) destinationFilePaths:destinationPath ? @[destinationPath] : nil];
                    
                } failure:^(NSString *destinationPath, NSError *error) { // 保存失败
                    
                    [self.indicatorView stopAnimating];
                    
                    [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCopyFailed) destinationFilePaths:destinationPath ? @[destinationPath] : nil];
                }];
            }
        }];
        
        [urls.firstObject stopAccessingSecurityScopedResource];
        
    } else {
        //授权失败
    }
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    
    NSLog(@"documentPickerWasCancelled");
}

#pragma mark
#pragma mark - 通知文件的添加/删除

- (void)postNotificationOfAddFilePath:(NSString *)filePath{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidAddFileNotification object:self.navigationController userInfo:filePath ? @{JKFileExplorerFileOperateDestinationFilePathsKey : filePath} : nil];
}

- (void)postNotificationOfDeleteFilePath:(NSString *)filePath{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidDeleteFileNotification object:self.navigationController userInfo:filePath ? @{JKFileExplorerFileOperateDestinationFilePathsKey : filePath} : nil];
    
}

#pragma mark
#pragma mark - 通知文件操作

- (void)addOperateFileNotifications{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willOperateFileNotification:) name:JKFileExplorerWillOperateFileNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didOperateFileNotification:) name:JKFileExplorerDidOperateFileNotification object:nil];
}

- (void)willOperateFileNotification:(NSNotification *)noti{
    
    NSArray *fileItems = [noti object];
    
    _operatingFileItems = [fileItems copy];
    
    [self willOperateFileItems:fileItems];
}

- (void)didOperateFileNotification:(NSNotification *)noti{
    
    NSArray *fileItems = [noti object];
    
    NSArray *destinationFilePaths = [noti.userInfo objectForKey:JKFileExplorerFileOperateDestinationFilePathsKey];
    
    JKFileExplorerFileOperateResult result = [[noti.userInfo objectForKey:JKFileExplorerFileOperateResultKey] integerValue];
    
    [self didOperateFileItems:fileItems destinationFilePaths:destinationFilePaths result:result];
}

- (void)postWillOperateFileNotificationWithItems:(NSArray <JKFileExplorerItem *> *)fileItems
                                    operateType:(JKFileExplorerFileOperateType)operateType{
    
    if (!fileItems || fileItems.count == 0) { return; }
    
    for (JKFileExplorerItem *fileItem in fileItems) {
        
        fileItem.isOperating = YES;
        fileItem.fileOperateType = operateType;
        
        !fileItem.fileInfoDidChange ? : fileItem.fileInfoDidChange(fileItem);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerWillOperateFileNotification object:fileItems userInfo:nil];
}

- (void)postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResult)result
                             destinationFilePaths:(NSArray <NSString *> *)destinationFilePaths{
    
    NSDictionary *dict = destinationFilePaths ?
    @{JKFileExplorerFileOperateResultKey : @(result),
      JKFileExplorerFileOperateDestinationFilePathsKey : destinationFilePaths} :
    @{JKFileExplorerFileOperateResultKey : @(result)};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidOperateFileNotification object:self.operatingFileItems userInfo:dict];
}

- (void)setOperatingFileItems:(NSArray <JKFileExplorerItem *> *)operatingFileItems{
    _operatingFileItems = [operatingFileItems copy];
    
    if (_operatingFileItems) {
        
        for (JKFileExplorerItem *item in _operatingFileItems) {
            
            JKFileExplorerItem *fileItem = [self.filePathItemDict objectForKey:item.filePath];
            
            if (fileItem) {
                
                fileItem.isOperating = YES;
                fileItem.fileOperateType = item.fileOperateType;
                
                !fileItem.fileInfoDidChange ? : fileItem.fileInfoDidChange(fileItem);
            }
        }
    }
    
    [self willOperateFileItems:_operatingFileItems];
}

- (void)willOperateFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    if (!fileItems || fileItems.count == 0) { return; }
    
    [self showOperateFileButton];
    
    JKFileExplorerItem *firstItem = [fileItems firstObject];
    
    if ([firstItem.fileDirectory isEqualToString:self.fileItem.filePath] &&
        firstItem.fileOperateType == JKFileExplorerFileOperateTypeMove) {
        
        self.pasteButton.enabled = NO;
    }
}

- (void)didOperateFileItems:(NSArray <JKFileExplorerItem *> *)fileItems
       destinationFilePaths:(NSArray <NSString *> *)destinationFilePaths
                    result:(JKFileExplorerFileOperateResult)result{
    
    NSInteger i = 0;
    
    NSInteger count = fileItems.count;
    
    __block NSInteger refreshIndex = 0;
    
    NSString *destinationFilePath = nil;
    
    BOOL shouldResortForDelete = NO;
    
    for (JKFileExplorerItem *fileItem in self.operatingFileItems) {
        
        fileItem.isOperating = NO;
        fileItem.fileOperateType = JKFileExplorerFileOperateTypeNone;
        
        !fileItem.fileInfoDidChange ? : fileItem.fileInfoDidChange(fileItem);
        
        destinationFilePath = [destinationFilePaths objectAtIndex:i];
        
        i++;
        
        switch (result) {
            case JKFileExplorerFileOperateResultMoveSuccess:
            {
                // 在当前文件下移走的
                if ([fileItem.fileDirectory isEqualToString:self.fileItem.filePath]) {
                    
                    [self refreshForDeleteFileWithPath:fileItem.filePath autoReload:NO];
                    
                    shouldResortForDelete = YES;
                    
                } else {
                    
                    JKFileExplorerItem *subItem = [self.filePathItemDict objectForKey:fileItem.fileDirectory];
                    
                    // 在当前文件夹的子文件夹中移走的
                    if (subItem) {
                        
                        // 没有打开下一个目录或者下一个目录不是移走文件的子文件夹
                        if (!self.nextVC || ![self.nextVC.fileItem.filePath isEqualToString:fileItem.fileDirectory]) {
                            
                            // 更新该子文件夹的子文件名列表
                            NSMutableArray *arrM = [NSMutableArray array];
                            [arrM addObjectsFromArray:subItem.subFileNameList];
                            [arrM removeObject:fileItem.fileName];
                            subItem.subFileNameList = arrM;
                            
                            !subItem.fileInfoDidChange ? : subItem.fileInfoDidChange(subItem);
                        }
                    }
                }
                
                // 移动到了当前目录
                if (destinationFilePath &&
                    [[destinationFilePath stringByDeletingLastPathComponent] isEqualToString:self.fileItem.filePath]) {
                    
                    [self refreshForNewFileWithPath:destinationFilePath autoResort:NO complete:^(JKFileExplorerItem *fileItem) {
                        
                        refreshIndex++;
                        
                        if (refreshIndex >= count) {
                            
                            [self resort];
                        }
                    }];
                }
            }
                break;
            case JKFileExplorerFileOperateResultCopySuccess:
            {
                // 复制到了当前目录
                if (destinationFilePath &&
                    [[destinationFilePath stringByDeletingLastPathComponent] isEqualToString:self.fileItem.filePath]) {
                    
                    [self refreshForNewFileWithPath:destinationFilePath autoResort:NO complete:^(JKFileExplorerItem *fileItem) {
                        
                        refreshIndex++;
                        
                        if (refreshIndex >= count) {
                            
                            [self resort];
                        }
                    }];
                }
            }
                break;
                
            default:
                break;
        }
        
        JKFileExplorerItem *item = [self.filePathItemDict objectForKey:fileItem.filePath];
        
        if (item) {
            
            item.isOperating = NO;
            item.fileOperateType = JKFileExplorerFileOperateTypeNone;
            
            !item.fileInfoDidChange ? : item.fileInfoDidChange(item);
        }
    }
    
    self.operatingFileItems = nil;
    
    [self hideOperateFileButton];
    
    if (shouldResortForDelete) {
        
        [self resort];
    }
}

- (void)showOperateFileButton{
    
    [self stopWifiTransfer];
    
    self.selectButton.hidden = YES;
    self.addButton.hidden = YES;
    
    self.pasteButton.hidden = NO;
    self.cancelOperateFileButton.hidden = NO;
}

- (void)hideOperateFileButton{
    
    self.pasteButton.hidden = YES;
    self.cancelOperateFileButton.hidden = YES;
    
    self.selectButton.hidden = NO;
    self.addButton.hidden = NO;
}

- (void)pasteButtonClick:(UIButton *)button{
    button.hidden = YES;
    
    // 无操作项目
    if (!self.operatingFileItems || self.operatingFileItems == 0) {
        
        [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCancel) destinationFilePaths:nil];
        
        return;
    }
    
    JKFileExplorerItem *firstItem = [self.operatingFileItems firstObject];
    
    // 操作项目在当前目录
    if ([firstItem.fileDirectory isEqualToString:self.fileItem.filePath]) {
        
        // 不允许移动到相同目录
        if (firstItem.fileOperateType == JKFileExplorerFileOperateTypeMove) {
            return;
        }
        
        // 复制到同一目录下
        if ((firstItem.fileOperateType == JKFileExplorerFileOperateTypeCopy)) {
            
            // 执行复制操作
            [self executeCopyFileItems:self.operatingFileItems];
        }
        
        return;
    }
    
    // 操作项目在不同目录
    
    switch (firstItem.fileOperateType) {
        case JKFileExplorerFileOperateTypeMove:
        {
            // 执行移动操作
            [self executeMoveFileItems:self.operatingFileItems];
        }
            break;
        case JKFileExplorerFileOperateTypeCopy:
        {
            // 执行复制操作
            [self executeCopyFileItems:self.operatingFileItems];
        }
            break;
            
        default:
            break;
    }
}

- (void)cancelOperateFileButtonClick:(UIButton *)button{
    
    [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCancel) destinationFilePaths:nil];
}

- (void)executeCopyFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    if (!fileItems || fileItems.count == 0) { return; }
    
    JKFileExplorerItem *firstItem = [fileItems firstObject];
    
    // 检查是否复制了自己本身到自己的目录下
    if ([firstItem.filePath isEqualToString:self.fileItem.filePath]) {
        
        [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCopyFailed) destinationFilePaths:nil];
        
        [self showStatusWithMessage:@"无法将自身复制到自身目录下!"];
        
        return;
    }
    
    [self.indicatorView startAnimating];
    
    dispatch_async([JKFileExplorerEngine explorerEngineQueue], ^{
       
        NSMutableArray *fromPaths = [NSMutableArray array];
        NSMutableArray *toPaths = [NSMutableArray array];
        
        for (JKFileExplorerItem *fileItem in fileItems) {
            
            NSString *toPath = [self.fileItem.filePath stringByAppendingPathComponent:fileItem.fileName];
            
            [toPaths addObject:toPath];
            
            [fromPaths addObject:fileItem.filePath];
        }
        
        // 复制文件
        [JKFileExplorerEngine multiCopyItemAtPaths:fromPaths toPaths:toPaths progress:^(CGFloat progress) {
            
            // TODO: JKTODO 复制进度
            
        } complete:^(NSArray<NSString *> *successPaths, NSArray<NSString *> *failurePaths) {
            
            [self.indicatorView stopAnimating];
            
            if (successPaths.count == 0) {
                
                [self showStatusWithMessage:@"复制失败！"];
                
                [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCopyFailed) destinationFilePaths:nil];
                
                return;
            }
            
            [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultCopySuccess) destinationFilePaths:successPaths];
            
            NSString *tip = nil;
            
            if (failurePaths.count > 0) {
                
                tip = [NSString stringWithFormat:@"复制成功%zd，复制失败%zd", successPaths.count, failurePaths.count];
                
            } else {
                
                tip = @"复制成功!";
            }
            
            [self showStatusWithMessage:tip];
        }];
    });
}

- (void)executeMoveFileItems:(NSArray <JKFileExplorerItem *> *)fileItems{
    
    if (!fileItems || fileItems.count == 0) { return; }
    
    JKFileExplorerItem *firstItem = [fileItems firstObject];
    
    // 检查是否移动了自己本身到自己的目录下
    if ([firstItem.filePath isEqualToString:self.fileItem.filePath]) {
        
        [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultMoveFailed) destinationFilePaths:nil];
        
        [self showStatusWithMessage:@"无法将自身移动到自身目录下!"];
        
        return;
    }
    
    dispatch_async([JKFileExplorerEngine explorerEngineQueue], ^{
        
        NSMutableArray *fromPaths = [NSMutableArray array];
        NSMutableArray *toPaths = [NSMutableArray array];
        
        for (JKFileExplorerItem *fileItem in fileItems) {
            
            NSString *toPath = [self.fileItem.filePath stringByAppendingPathComponent:fileItem.fileName];
            
            [toPaths addObject:toPath];
            
            [fromPaths addObject:fileItem.filePath];
        }
        
        [JKFileExplorerEngine multiMoveItemAtPaths:fromPaths toPaths:toPaths progress:^(CGFloat progress) {
            
            // TODO: JKTODO 移动进度
            
        } complete:^(NSArray<NSString *> *successPaths, NSArray<NSString *> *failurePaths) {
            
            [self.indicatorView stopAnimating];
            
            if (successPaths.count == 0) {
                
                [self showStatusWithMessage:@"移动失败！"];
                
                [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultMoveFailed) destinationFilePaths:nil];
                
                return;
            }
            
            [self postDidOperateFileNotificationWithResult:(JKFileExplorerFileOperateResultMoveSuccess) destinationFilePaths:successPaths];
            
            NSString *tip = nil;
            
            if (failurePaths.count > 0) {
                
                tip = [NSString stringWithFormat:@"移动成功%zd，移动失败%zd", successPaths.count, failurePaths.count];
                
            } else {
                
                tip = @"移动成功!";
            }
            
            [self showStatusWithMessage:tip];
        }];
    });
}

#pragma mark
#pragma mark - 外界文件操作，通过通知来更新

- (void)addOutsideOperateFileNotifications{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outSideAddFileNotification:) name:JKFileExplorerDidAddFileNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(outSideDeleteFileNotification:) name:JKFileExplorerDidDeleteFileNotification object:nil];
}

- (void)outSideAddFileNotification:(NSNotification *)noti{
    
    if (noti.object == self.navigationController) {
        
        return;
    }
    
    NSString *destinationPath = [noti.userInfo objectForKey:JKFileExplorerFileOperateDestinationFilePathsKey];
    
    [self outSideAddFileWithPath:destinationPath];
}

- (void)outSideDeleteFileNotification:(NSNotification *)noti{
    
    if (noti.object == self.navigationController) {
        
        return;
    }
    
    NSString *destinationPath = [noti.userInfo objectForKey:JKFileExplorerFileOperateDestinationFilePathsKey];
    
    [self outSideDeleteFileWithPath:destinationPath];
}

- (void)outSideAddFileWithPath:(NSString *)filePath{
    
    if (!filePath || ![JKFileManager isExistsAtPath:filePath]) { return; }
    
    NSString *directory = [filePath stringByDeletingLastPathComponent];
    
    // 在当前文件夹下添加的
    if ([directory isEqualToString:self.fileItem.filePath]) {
        
        [self refreshForNewFileWithPath:filePath autoResort:YES complete:nil];
        
    } else { // 在其它文件夹下添加的
        
        JKFileExplorerItem *subItem = [self.filePathItemDict objectForKey:directory];
        
        if ([self.filePathItemDict objectForKey:directory]) { // 当前文件夹的子文件夹下
            
            // 没有打开下一个目录或者下一个目录不是操作文件的子文件夹
            if (!self.nextVC || ![self.nextVC.fileItem.filePath isEqualToString:directory]) {
                
                // 更新该子文件夹的子文件名列表
                NSMutableArray *arrM = [NSMutableArray array];
                [arrM addObjectsFromArray:subItem.subFileNameList];
                [arrM addObject:[filePath lastPathComponent]];
                subItem.subFileNameList = arrM;
                
                !subItem.fileInfoDidChange ? : subItem.fileInfoDidChange(subItem);
            }
        }
    }
}

- (void)outSideDeleteFileWithPath:(NSString *)filePath{
    
    if ([JKFileManager isExistsAtPath:filePath]) { return; }
    
    NSString *directory = [filePath stringByDeletingLastPathComponent];
    
    // 在当前文件夹下删除的
    if ([directory isEqualToString:self.fileItem.filePath]) {
        
        [self refreshForDeleteFileWithPath:filePath autoReload:YES];
        
    } else { // 在其它文件夹下删除的
        
        JKFileExplorerItem *subItem = [self.filePathItemDict objectForKey:directory];
        
        if ([self.filePathItemDict objectForKey:directory]) { // 当前文件夹的子文件夹下
            
            // 没有打开下一个目录或者下一个目录不是操作文件的子文件夹
            if (!self.nextVC || ![self.nextVC.fileItem.filePath isEqualToString:directory]) {
                
                // 更新该子文件夹的子文件名列表
                NSMutableArray *arrM = [NSMutableArray array];
                [arrM addObjectsFromArray:subItem.subFileNameList];
                [arrM removeObject:[filePath lastPathComponent]];
                subItem.subFileNameList = arrM;
                
                !subItem.fileInfoDidChange ? : subItem.fileInfoDidChange(subItem);
            }
        }
    }
}

#pragma mark
#pragma mark - 检查重名，并返回合适的文件路径

- (NSString *)checkDuplicationNameOperateFileItem:(JKFileExplorerItem *)fileItem{
    
    NSString *fileName = fileItem.fileName;
    
    NSString *destinationPath = [self.fileItem.filePath stringByAppendingPathComponent:fileName];
    
    return [JKFileExplorerEngine checkDuplicationNameWithFilePath:destinationPath isFolder:fileItem.isFolder];
}

#pragma mark
#pragma mark - 隐藏cell的更多操作

- (void)hideCellMoreActionContainerView{
    
    if (!self.currentMoreAtionFileItem ||
        !self.currentMoreAtionFileItem.showMoreAction) {
        
        return;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[(self.showSearchResult ? self.searchFileItemArr : self.fileItemArr) indexOfObject:self.currentMoreAtionFileItem] inSection:0];
    
    JKFileExploreCollectionViewCell *cell = (JKFileExploreCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    NSArray *visibleCells = [self.collectionView visibleCells];
    
    if ([visibleCells containsObject:cell]) {
        
        [cell hideMoreActionContainerView];
    }
    
    self.currentMoreAtionFileItem.showMoreAction = NO;
    self.currentMoreAtionFileItem = nil;
}

#pragma mark
#pragma mark - 清除新文件的背景色

- (void)refreshClearNewFileColor{
    
    if (self.fileNewItems.count == 0) { return; }
    
    [self.fileNewItems enumerateObjectsUsingBlock:^(JKFileExplorerItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        obj.isNew = NO;
        
        !obj.fileInfoDidChange ? : obj.fileInfoDidChange(obj);
    }];
    
    [self.fileNewItems removeAllObjects];
}

#pragma mark
#pragma mark - textfield弹框

- (void)showTextfieldAlertWithTitle:(NSString *)title
                            message:(NSString *)message
                               text:(NSString *)text
                        placeholder:(NSString *)placeholder
                        verifyTitle:(NSString *)verifyTitle
                       verifyAction:(void(^)(NSString *text))verifyAction {
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    __block UITextField *outTextField;
    
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        outTextField = textField;
        textField.placeholder = placeholder;
        
        if (text) {
            
            textField.text = text;
        }
    }];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:verifyTitle style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if (!outTextField.hasText) {

            [self showStatusWithMessage:@"输入有误！"];
            
            return;
        }
        
        !verifyAction ? : verifyAction(outTextField.text);
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark
#pragma mark - Property

- (NSMutableDictionary *)filePathItemDict{
    if (!_filePathItemDict) {
        _filePathItemDict = [NSMutableDictionary dictionary];
    }
    return _filePathItemDict;
}

- (NSMutableArray *)fileItemArr{
    if (!_fileItemArr) {
        _fileItemArr = [NSMutableArray array];
    }
    return _fileItemArr;
}

- (NSMutableArray *)searchFileItemArr{
    if (!_searchFileItemArr) {
        _searchFileItemArr = [NSMutableArray array];
    }
    return _searchFileItemArr;
}

- (NSMutableArray *)fileNewItems{
    if (!_fileNewItems) {
        _fileNewItems = [NSMutableArray array];
    }
    return _fileNewItems;
}

- (NSMutableArray *)selectedFileItems{
    if (!_selectedFileItems) {
        _selectedFileItems = [NSMutableArray array];
    }
    return _selectedFileItems;
}

- (NSMutableArray *)filePreviewItemArr{
    if (!_filePreviewItemArr) {
        _filePreviewItemArr = [NSMutableArray array];
    }
    return _filePreviewItemArr;
}

- (NSMutableArray *)searchFilePreviewItemArr{
    if (!_searchFilePreviewItemArr) {
        _searchFilePreviewItemArr = [NSMutableArray array];
    }
    return _searchFilePreviewItemArr;
}

- (UIButton *)wifiTransferButton{
    if (!_wifiTransferButton) {
        UIButton *wifiTransferButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        wifiTransferButton.frame = CGRectMake(49, 0, self.tabBar.frame.size.width - 98, 49);
        wifiTransferButton.titleLabel.font = [UIFont systemFontOfSize:11];
        wifiTransferButton.titleLabel.numberOfLines = 0;
        wifiTransferButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [wifiTransferButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [self.tabBar insertSubview:wifiTransferButton atIndex:0];
        
        [wifiTransferButton addTarget:self action:@selector(wifiTransferInfoButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        
        _wifiTransferButton = wifiTransferButton;
    }
    return _wifiTransferButton;
}
@end
